package br.ufpe.cin.mac.middleware.connectors.abstracts;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import br.ufpe.cin.mac.middleware.connectors.AbstractConnector;
import br.ufpe.cin.mac.util.Constants;
import br.ufpe.cin.mac.util.Message;

/**
 * Class Mom
 * 
 * @author Osmany
 * @author Rafael Roque
 * 
 */
public class Mom extends AbstractConnector implements MomMBean {

	public Mom(String compFrom, String compTo, String connConcrete) {
		super(Mom.class.getCanonicalName(), compFrom, compTo, connConcrete);
	}

	/***************************************************************************
	 * ***********************************************************
	 * ******************** INTERNAL METHODS *********************
	 * ***********************************************************
	 */

	protected void msgManager(Message msg) {
		List<String> ops = msg.readOperations();
		Iterator<String> it = ops.iterator();
		while (it.hasNext()) {
			String op = (String) it.next();
			// System.err.println(op);
			if (op.equals(Constants.SEND_REQUEST))
				sendRequest(msg);

			else if (op.equals(Constants.SEND_RESPONSE))
				sendResponse(msg);

			else if (op.equals(Constants.SEND_PROXY))
				sendProxy(msg);

			else
				System.err.println(op + " Not operation available");
		}
	}

	private void sendRequest(Message msg) {
		msg.setConnector("Middleware:Type=AbstractConnector,name="
				+ this.getClass().getSimpleName());
		loadInterceptors(msg, Constants.REQUEST);
		sendNotification(msg.hashCode(), "invS");
	}

	private void sendResponse(Message msg) {
		msg.removeAllInterceptors();
		loadInterceptors(msg, Constants.RESPONSE);
		sendNotification(msg.hashCode(), "terC");
	}

	private void sendProxy(Message msg) {
		msg.removeAllInterceptors();
		List<String> ops = new LinkedList<String>();

		ops.add("Jms");
		msg.addInterceptor("Proxy", ops);

		/* MUDAR */
		sendNotification(msg.hashCode(), "invS");
	}

	private void loadInterceptors(Message msg, String type) {

		msg.removeAllInterceptors();
		List<String> ops = new LinkedList<String>();
		String connConcrete = "";

		if (type == Constants.REQUEST) {
			connConcrete = this.connConcrete.replaceAll("Server", "Client");
			ops.add("sendRequest");
		} else {
			connConcrete = this.connConcrete.replaceAll("Client", "Server");
			ops.add("sendResponse");
		}

		msg.addInterceptor(this.compFrom, ops);
		msg.addInterceptor(this.compTo, ops);
		msg.addInterceptor(connConcrete, ops);
		msg.addInterceptor(this.compTo, ops);
		msg.addInterceptor(this.compFrom, ops);
		if (type == Constants.REQUEST) {
			List<String> op = new LinkedList<String>();
			op.add(Constants.SEND_PROXY);
			msg.addInterceptor("Middleware:Type=AbstractConnector,name="
					+ this.getClass().getSimpleName(), op);
		}
	}

	public void setHost(String host) {
		// TODO Auto-generated method stub
		
	}
}
